package com.cheer.ba.view.adapter;

import android.content.Intent;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.Html;
import android.text.Layout;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cheer.ba.R;
import com.cheer.ba.app.App;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.choosepic.ui.GalleryActivity;
import com.cheer.ba.choosepic.ui.GalleryAty;
import com.cheer.ba.choosepic.util.Bimp;
import com.cheer.ba.choosepic.util.ImageItem;
import com.cheer.ba.choosepic.util.PublicWay;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.model.CheerCircleModel;
import com.cheer.ba.model.CommentModel;
import com.cheer.ba.model.OilDetailBannerModel;
import com.cheer.ba.model.TagModel;
import com.cheer.ba.utils.ImageUtils;
import com.cheer.ba.utils.LogUtils;
import com.cheer.ba.utils.Protect;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.activity.CheerCircleAty;
import com.cheer.ba.view.activity.FullScreenAty;
import com.cheer.ba.view.base.CommonAdapter;
import com.cheer.ba.view.base.ViewHolder;
import com.cheer.ba.widget.MultiImageView;
import com.cheer.ba.widget.MyListView;

import org.xml.sax.XMLReader;

import java.util.ArrayList;
import java.util.List;

/**
 * 加油圈
 * Created by Hq on 2017/7/7.
 */
public class CheerCircleAdp extends BaseQuickAdapter<CheerCircleModel, BaseViewHolder> {

    private final int MAX_LINE_COUNT = 4;

    private final int STATE_UNKNOW = -1;

    private final int STATE_NOT_OVERFLOW = 1;//文本行数不能超过限定行数

    private final int STATE_COLLAPSED = 2;//文本行数超过限定行数，进行折叠

    private final int STATE_EXPANDED = 3;//文本超过限定行数，被点击全文展开

    private SparseArray<Integer> mTextStateList;

    private int width;

    public CheerCircleAdp(@LayoutRes int layoutResId, @Nullable List<CheerCircleModel> data) {
        super(layoutResId, data);
        mTextStateList = new SparseArray<>();
    }

    public CheerCircleAdp(@LayoutRes int layoutResId, @Nullable List<CheerCircleModel> data, int width) {
        super(layoutResId, data);
        this.width = width;
        mTextStateList = new SparseArray<>();
    }

    public void clearSparse() {
        mTextStateList.clear();
    }

    @Override
    protected void convert(final BaseViewHolder helper, final CheerCircleModel item) {
        if (null != item) {
            helper.addOnClickListener(R.id.id_jump_circle_detail_rela);
            ImageUtils.showCircleImg(mContext, Protect.setPic(item.custImg), R.drawable.ic_user_head, R.drawable.ic_user_head, (ImageView) helper.getView(R.id.id_circle_img));
            helper.setText(R.id.id_circle_user_name, item.custNname);
            helper.setText(R.id.id_circle_user_time, StringUtils.getDetailStr(item.createTime));
            if (TextUtils.equals(item.custId, Session.getUserId())) {
                helper.getView(R.id.id_circle_del_txt).setVisibility(View.VISIBLE);
//                helper.getView(R.id.id_circle_line).setVisibility(View.VISIBLE);
                helper.addOnClickListener(R.id.id_circle_del_txt);
            } else {
                helper.getView(R.id.id_circle_del_txt).setVisibility(View.INVISIBLE);
//                helper.getView(R.id.id_circle_line).setVisibility(View.INVISIBLE);
            }
            //内容区
            LinearLayout mLinear = helper.getView(R.id.id_look_content_linear);
            //内容
            final TextView mTxtContext = helper.getView(R.id.id_circle_content_txt);
            //查看全部
            TextView mTxtLookAll = helper.getView(R.id.id_circle_load_txt);
            String context = item.title;
            if (StringUtils.isEmpty(context)) {
                mLinear.setVisibility(View.GONE);
            } else {
                mLinear.setVisibility(View.VISIBLE);
                handContentTxt(helper.getAdapterPosition(), item.tagList, mTxtContext, mTxtLookAll, item.title);
            }
            MultiImageView mMultiImg = helper.getView(R.id.id_circle_pic_list);
            final List<OilDetailBannerModel> mPics = item.fileList;
            if (null != mPics && !mPics.isEmpty()) {
                mMultiImg.setVisibility(View.VISIBLE);
                mMultiImg.setList(mPics, item.dynamicType);
                mMultiImg.setOnItemClickListener(new MultiImageView.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position, int fileType, String videoUrl) {
                        if (fileType == 3) {
                            //视频
                            Intent intent = new Intent(mContext, FullScreenAty.class);
                            intent.putExtra(IntentKey.General.KEY_URL, videoUrl);
                            intent.putExtra(IntentKey.General.KEY_BOOLEAN, false);
                            mContext.startActivity(intent);
                        } else {
                            //图片
                            Bimp.tempSelectBitmap.clear();
                            for (OilDetailBannerModel model : mPics) {
                                ImageItem item = new ImageItem(model.fileStatus, Protect.setPic(model.fileUrl));
                                Bimp.tempSelectBitmap.add(item);
                            }
                            Intent intent = new Intent(mContext, GalleryAty.class);
                            intent.putExtra(IntentKey.General.KEY_POS, position);
                            intent.putExtra(IntentKey.General.KEY_BOOLEAN, false);
                            mContext.startActivity(intent);
                        }
                    }
                });
            } else {
                mMultiImg.setVisibility(View.GONE);
            }
            //位置
            if (StringUtils.isEmpty(item.location)) {
                helper.setText(R.id.id_circle_location_txt, "");
            } else {
                helper.setText(R.id.id_circle_location_txt, item.location);
            }
            //点赞
            helper.addOnClickListener(R.id.id_circle_like_linear);
            ImageView mZanImg = helper.getView(R.id.id_circle_zan_img);
            if (item.goodStatus == 1) {
                mZanImg.setSelected(true);
            } else {
                mZanImg.setSelected(false);
            }
            LogUtils.LogD("点赞", item.goodCount + "=======");
            if (item.goodCount != 0) {
                helper.setText(R.id.id_circle_zan_txt, item.goodCount + "");
            } else {
                helper.setText(R.id.id_circle_zan_txt, "");
            }
            //是否可以转发
            helper.addOnClickListener(R.id.id_forward_rela);
            MyListView mCommentRela = helper.getView(R.id.id_circle_listv);
            //所有
            final List<CommentModel> mComments = item.getCommentList();
            //评论
            helper.addOnClickListener(R.id.id_circle_comment_txt);
            LogUtils.LogD("评论数", mComments.size() + "=========");
            if (mComments.size() != 0) {
                helper.setText(R.id.id_circle_comment_txt, mComments.size() + "");
            } else {
                helper.setText(R.id.id_circle_comment_txt, "");
            }
            //5条
            final List<CommentModel> mSaveComment = new ArrayList<CommentModel>();
            //展示
            final List<CommentModel> mRefreshComment = new ArrayList<CommentModel>();
            if (mComments.size() > 0) {
                mCommentRela.setVisibility(View.VISIBLE);
                if (mComments.size() > 5) {
                    for (int i = 0; i < 5; i++) {
                        CommentModel model = mComments.get(i);
                        if (i == 4) {
                            model.setShow(true);
                            CommentModel m = mComments.get(mComments.size() - 1);
                            m.setShow(true);
                        }
                        mSaveComment.add(mComments.get(i));
                    }
                } else {
                    mSaveComment.addAll(mComments);
                }
                mRefreshComment.addAll(mSaveComment);

                final CommonAdapter<CommentModel> mAdp = new CommonAdapter(mContext, mRefreshComment, R.layout.layout_comment) {
                    @Override
                    public void convert(ViewHolder helperChild, Object item) {
                        CommentModel model = (CommentModel) item;
                        //评论
                        TextView mTxtContent = helperChild.getView(R.id.id_circle_cment_content_txt);
                        //时间
                        helperChild.setText(R.id.id_circle_cment_time_txt, StringUtils.getDetailStr(model.releaseDate));
                        //展开全部
                        final TextView mTxtALL = helperChild.getView(R.id.id_circle_all_txt);
                        mTxtALL.setVisibility(View.GONE);
                        if (model.isShow()) {
                            if (helperChild.getPosition() == getDatas().size() - 1) {
                                mTxtALL.setVisibility(View.VISIBLE);
                                if (getCount() > 5) {
                                    mTxtALL.setText("收起评论");
                                } else {
                                    mTxtALL.setText("展开全部评论");
                                }
                            }
                        }

                        mTxtALL.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String msg = mTxtALL.getText().toString().trim();
                                if (TextUtils.equals(msg, "展开全部评论")) {
                                    setDatas(mComments);
                                    notifyDataSetChanged();
                                } else {
                                    setDatas(mSaveComment);
                                    notifyDataSetChanged();
                                }
                            }
                        });
                        //处理内容
                        String html = "<font color='#333333'> " + model.custNname + " </font>";
                        //1评论 2回复
                        int cmtType = model.cmtType;
                        if (cmtType == 1) {
                            html += ": ";
                        } else {
                            html += " 回复 " + "<font color='#333333'> " + model.replyCustNname + " </font>" + ": ";
                        }
                        if (model.delFlag == 0) {
                            html += model.context;
                        } else {
                            html += "<font color='#999999'> " + "评论已删除" + " </font>";
                        }
                        mTxtContent.setText(Html.fromHtml(html));
                    }
                };
                mCommentRela.setAdapter(mAdp);
                mCommentRela.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        CommentModel model = (CommentModel) mAdp.getItem(position);
                        mListener.onSelfItemClick(item, model);
                    }
                });
            } else {
                mCommentRela.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 处理中间文字部分
     */
    public void handContentTxt(final int pos, final List<TagModel> tags, final TextView tContentv, final TextView tAll, final String context) {
        if (!StringUtils.isEmpty(context)) {
            int state = mTextStateList.get(pos, STATE_UNKNOW);
            //如果该item是第一次初始化，则获取文本的行数
            if (state == STATE_UNKNOW) {
                tContentv.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        tContentv.getViewTreeObserver().removeOnPreDrawListener(this);
                        //如果内容显示的行数大于限定显示行数
                        if (tContentv.getLineCount() > MAX_LINE_COUNT) {
                            //设置最大显示行数
                            tContentv.setMaxLines(MAX_LINE_COUNT);
                            //让其显示全文的文本框状态为显示
                            tAll.setVisibility(View.VISIBLE);
                            tAll.setText("全部");
                            mTextStateList.put(pos, STATE_COLLAPSED);
                        } else {
                            //显示全文隐藏
                            tAll.setVisibility(View.GONE);
                            //让其不能超过限定的行数
                            mTextStateList.put(pos, STATE_NOT_OVERFLOW);
                        }
                        return true;
                    }
                });
                //设置文本的最大行数，为整数的最大数值
                tContentv.setMaxLines(Integer.MAX_VALUE);
            } else {
                //如果之前已经初始化过了，则使用保存的状态，无需在获取一次
                switch (state) {
                    case STATE_NOT_OVERFLOW:
                        tAll.setVisibility(View.GONE);
                        break;
                    case STATE_COLLAPSED:
                        tContentv.setMaxLines(MAX_LINE_COUNT);
                        tAll.setVisibility(View.VISIBLE);
                        tAll.setText("全部");
                        break;
                    case STATE_EXPANDED:
                        tContentv.setMaxLines(Integer.MAX_VALUE);
                        tAll.setVisibility(View.VISIBLE);
                        tAll.setText("收起");
                        break;
                }
            }
        }
        //标签
        StringBuilder sb = new StringBuilder();
        if (null != tags && !tags.isEmpty()) {
            for (int i = 0; i < tags.size(); i++) {
                TagModel model = tags.get(i);
                String str = "<font color='#E69215'><tag>" + " #" + model.tagName + "# " + "</tag></font>" + "、";
                sb.append(str);
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        tContentv.setText(Html.fromHtml(sb.toString() + context, null, new Html.TagHandler() {
            int sIndex = 0;
            int eIndex = 0;

            @Override
            public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
                if (opening) {
                    if (tag.toLowerCase().equals("tag")) {
                        sIndex = output.length();
                    }
                } else {
                    if (tag.toLowerCase().equals("tag")) {
                        eIndex = output.length();
                        output.setSpan(new MxgsaSpan(tags, output.toString()), sIndex, eIndex, Spanned.SPAN_MARK_MARK);
                    }
                }
            }
        }));
        tContentv.setClickable(true);
        tContentv.setMovementMethod(LinkMovementMethod.getInstance());
        tContentv.setOnTouchListener(new LinkMovementMethodOverride());

        //设置显示和收起的点击事件
        tAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int state = mTextStateList.get(pos, STATE_UNKNOW);
                if (state == STATE_COLLAPSED) {
                    tContentv.setMaxLines(Integer.MAX_VALUE);
                    tAll.setText("收起");
                    mTextStateList.put(pos, STATE_EXPANDED);
                } else if (state == STATE_EXPANDED) {
                    tContentv.setMaxLines(MAX_LINE_COUNT);
                    tAll.setText("全部");
                    mTextStateList.put(pos, STATE_COLLAPSED);
                }
            }
        });
    }

    private class MxgsaSpan extends ClickableSpan implements View.OnClickListener {

        private String mstr;
        private List<TagModel> tags;

        public MxgsaSpan(List<TagModel> tags, String mstr) {
            this.mstr = mstr;
            this.tags = tags;
        }

        @Override
        public void onClick(View widget) {
            String msg = mstr.replaceAll("#", "").replaceAll(" ", "").trim();
            TagModel tagModel = null;
            String mSave = "";
            if (msg.contains("、")) {
                String[] split = msg.split("、");
                for (TagModel model : tags) {
                    if (TextUtils.equals(model.tagName, split[split.length - 1])) {
                        tagModel = model;
                    } else {
                        mSave = split[split.length - 1];
                    }
                }
            } else {
                TagModel model = tags.get(0);
                tagModel = model;
            }
            if (null != tagModel) {
                Intent intent = new Intent(mContext, CheerCircleAty.class);
                intent.putExtra(IntentKey.General.KEY_ID, tagModel.getId());
                intent.putExtra(IntentKey.General.KEY_DES, tagModel.getTitle());
                mContext.startActivity(intent);
            } else {
                ToastUtil.showToast(mSave);
            }
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(App.getContext().getResources().getColor(R.color.color_main));
            ds.setUnderlineText(false);
        }
    }

    public class LinkMovementMethodOverride implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            TextView widget = (TextView) v;
            Object text = widget.getText();
            if (text instanceof Spanned) {
                Spanned buffer = (Spanned) text;

                int action = event.getAction();

                if (action == MotionEvent.ACTION_UP
                        || action == MotionEvent.ACTION_DOWN) {
                    int x = (int) event.getX();
                    int y = (int) event.getY();

                    x -= widget.getTotalPaddingLeft();
                    y -= widget.getTotalPaddingTop();

                    x += widget.getScrollX();
                    y += widget.getScrollY();

                    Layout layout = widget.getLayout();
                    int line = layout.getLineForVertical(y);
                    int off = layout.getOffsetForHorizontal(line, x);

                    ClickableSpan[] link = buffer.getSpans(off, off,
                            ClickableSpan.class);

                    if (link.length != 0) {
                        if (action == MotionEvent.ACTION_UP) {
                            link[0].onClick(widget);
                        } else if (action == MotionEvent.ACTION_DOWN) {
                            // Selection only works on Spannable text. In our case setSelection doesn't work on spanned text
                            //Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]));
                        }
                        return true;
                    }
                }
            }
            return false;
        }
    }

    public onSelfChildItemClick mListener;

    public interface onSelfChildItemClick {
        void onSelfItemClick(CheerCircleModel cheerCircleModel, CommentModel commentModel);
    }

    public void setOnSelfChildItemClick(onSelfChildItemClick mListener) {
        this.mListener = mListener;
    }
}